﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class D09_Coroutine1 : MonoBehaviour
{
    private void OnGUI()
    {
        if (GUILayout.Button("开启协同方法"))
        {
            StartCoroutine("Test1");//方式1   可以通过StopCoroutine("Test1") 停止
                                    // StartCoroutine(Test1());//方式2   只能通过StopAllCoroutines()//停止
        }

        if (GUILayout.Button("理解协同"))
        {
            StartCoroutine("Test2");
        }

        if (GUILayout.Button("批量生成怪物"))
        {
            StartCoroutine("Test3");
        }
    }

    //案例  先打印 "A"  两秒后打印 "B"
    private IEnumerator Test1()
    {
        while (true)
        {
            print("A");
            yield return new WaitForSeconds(2);
            print("B");
            yield return new WaitForSeconds(2);
            print("C");
            yield return new WaitForSeconds(2);
        }
    }

    private IEnumerator Test2()
    {
        while (true)
        {
            print("协同");

            yield return null;
        }
    }

    //分批次生成怪物   第批  5个小兵  间隔1秒1个     第二批5个大兵 间隔2秒1个    Boos1个

    private IEnumerator Test3()
    {
        for (int i = 0; i < 5; i++)
        {
            print("生成1个小兵");
            yield return new WaitForSeconds(1);
        }

        for (int i = 0; i < 5; i++)
        {
            print("生成1个大兵");
            yield return new WaitForSeconds(2);
        }

        yield return new WaitForSeconds(3);

        print("生成Boss");
    }
}
public class D09_Coroutine2 : MonoBehaviour
{
    private IEnumerator enumerator;//迭代器
    private void OnGUI()
    {
        if (GUILayout.Button("拿到迭代器"))
        {
            enumerator = Test();
        }

        if (GUILayout.Button("MoveNext"))
        {
            enumerator.MoveNext();// 执行到下一个 yield return  ,返回的bool值表示 后面还有没有
            print(enumerator.Current);
        }
    }

    private IEnumerator Test()
    {
        print("A");
        yield return 1;

        print("B");
        yield return 2;

        print("C");
        yield return 3;
    }

    //协同程序的本质就是   Unity在每一帧检查 上次  yield return 后的条件是否满足,满足就继续MoveNext
}
//演示  并行执行和顺序执行
public class D09_Coroutine : MonoBehaviour
{
    private void OnGUI()
    {
        if (GUILayout.Button("同时执行"))
        {
            StartCoroutine("Test1");
            StartCoroutine("Test2");
        }

        if (GUILayout.Button("顺序执行"))
        {
            StartCoroutine("Fun");
        }
    }

    private IEnumerator Fun()
    {
        yield return StartCoroutine("Test1");//可以等待协同程序完成
        yield return StartCoroutine("Test2");
    }

    private IEnumerator Test1()
    {
        for (int i = 0; i < 10; i++)
        {
            print(1);
            yield return new WaitForSeconds(1);
        }
    }
    private IEnumerator Test2()
    {
        for (int i = 0; i < 10; i++)
        {
            print("A");
            yield return new WaitForSeconds(1);
        }
    }
}